package org.springforge.forgeweb.mvc;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.StreamTokenizer;
import java.util.ArrayList;

import javax.naming.NamingException;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import org.springforge.ldap.service.LdapService;


@Controller
public class ProjetController {
    
	String projet_path="C:/Projet OSGI/projet svn/cpcprojet/projets_example";
	
	@Autowired
	protected LdapService ldapService = null;
	
    @RequestMapping(value="/projet/index.html")
    public void index(@RequestParam(value="new_projet",required=false) String nom_projet,HttpSession session, Model model){
    	String username = (String) session.getAttribute("user");
    	
    	try{
    		if(nom_projet!=null)
        	{
        		createProject(nom_projet, ldapService.getFirstName(username), ldapService.getLastName(username));
        	}
    	model.addAttribute(	"firstname",
    						ldapService.getFirstName(username));
    	model.addAttribute(	"lastname",  	
    						ldapService.getLastName(username));
    	model.addAttribute(	"email",  	
    						username);
    	model.addAttribute("projets",getProjects(ldapService.getFirstName(username),ldapService.getLastName(username)));
    	}catch(NamingException e){e.printStackTrace();}
    }
    
    @RequestMapping(value="/projet/home.html")
    public void home(@RequestParam(value="svn",required=false) String nom_svn,@RequestParam(value="projet") String projet,HttpSession session, Model model){
    	String username = (String) session.getAttribute("user");
    	try{
    	if(nom_svn!=null)addSVN(projet, nom_svn);
    	model.addAttribute(	"firstname",
    						ldapService.getFirstName(username));
    	model.addAttribute(	"lastname",  	
    						ldapService.getLastName(username));
    	model.addAttribute(	"email",  	
    						username);
    	model.addAttribute("projet_name",projet);
    	model.addAttribute("projet_svn",getSVN(projet));
    	model.addAttribute("svn_check",getOption(projet, "svn"));
    	model.addAttribute("mail_check",getOption(projet, "mailing"));
    	model.addAttribute("isAdmin",isAdmin(projet, ldapService.getFirstName(username), ldapService.getLastName(username)));
    	}catch(NamingException e){e.printStackTrace();}
    }
    
    @RequestMapping(value="/projet/admin.html")
    public void admin(@RequestParam(value="show",required=false) String show_form,
    		@RequestParam(value="show_svn",required=false) String show_svn,
    		@RequestParam(value="show_mailing",required=false) String show_mailing,
    		@RequestParam(value="add_user",required=false) String add_user,
    		@RequestParam(value="nom_user",required=false) String nom_user,
    		@RequestParam(value="prenom_user",required=false) String prenom_user,
    		@RequestParam(value="projet")
    		String projet,HttpSession session, Model model){
    	String username = (String) session.getAttribute("user");
    	try{
    	model.addAttribute(	"firstname",
    						ldapService.getFirstName(username));
    	model.addAttribute(	"lastname",  	
    						ldapService.getLastName(username));
    	model.addAttribute(	"email",  	
    						username);
    	model.addAttribute("projet_name",projet);
    	if(add_user!=null&&nom_user!=null&&prenom_user!=null)
    	{
    		addUser(projet, prenom_user, nom_user);
    	}
    	if(show_form!=null)
    	{
	    	if(show_svn!=null)
	    	{
	    		setOption(projet, "svn", "true");
	    	}
	    	else setOption(projet, "svn", "false");
	    	if(show_mailing!=null)
	    	{
	    		setOption(projet, "mailing", "true");
	    	}
	    	else setOption(projet, "mailing", "false");
    	}
    	String temp="";
    	if(getOption(projet, "svn").equals("true"))temp="checked";
    	model.addAttribute("svn_check",temp);
    	temp="";
    	if(getOption(projet, "mailing").equals("true"))temp="checked";
    	model.addAttribute("mail_check",temp);
    	model.addAttribute("users",getUsers(projet));
    	}catch(NamingException e){e.printStackTrace();}
    }
    
    private boolean isAdmin(String projet,String firstname,String lastname)
    {
    	if(getOption(projet, "admin").toLowerCase().equals(firstname.toLowerCase()+"."+lastname.toLowerCase()))
    	{
    		return true;
    	}
    	else return false;
    }
    
    private ArrayList getProjects(String firstname,String lastname)
    {
    	String[] listeFichiers; 
    	File repertoire = new File(projet_path); 
    	
    	listeFichiers = repertoire.list();
    	ArrayList retour= new ArrayList<String>();
    	for (int i = 0; i < listeFichiers.length; i++) {
    		File repertoire2 = new File(projet_path+"/"+listeFichiers[i]+"/user/"+firstname.toLowerCase()+"."+lastname.toLowerCase()+".txt");
    		if(repertoire2.exists())
    		{
    		retour.add(listeFichiers[i]);
    		}
    	}
    	return retour;
    }
    
    private ArrayList getUsers(String projet)
    {
    	String[] listeFichiers;
    	File repertoire = new File(projet_path+"/"+projet+"/user");     	
    	listeFichiers = repertoire.list();
    	ArrayList retour= new ArrayList<String>();
    	for (int i = 0; i < listeFichiers.length; i++) {
    		retour.add(listeFichiers[i].replace(".txt", "").replace(".", " "));
    	}
    	return retour;
    }
    
    private void addUser(String projet,String firstname,String lastname)
    {
    	File fichier = new File(projet_path+"/"+projet+"/user/"+firstname.toLowerCase()+"."+lastname.toLowerCase()+".txt");
	    try {
			fichier.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
    
    private void createProject(String nom, String firstname,String lastname)
    {
    	new File(projet_path+"/"+nom).mkdir(); 
    	new File(projet_path+"/"+nom+"/user").mkdir(); 
    	new File(projet_path+"/"+nom+"/svn").mkdir(); 
    	new File(projet_path+"/"+nom+"/option").mkdir(); 
    	addUser(nom,firstname,lastname);
    	setOption(nom, "admin", firstname+"."+lastname);
    	setOption(nom, "svn", "true");
    	setOption(nom, "mailing", "true");

    }
    
    private void setOption(String projet, String option, String value)
    {
    	new File(projet_path+"/"+projet+"/option/"+option).delete();
    	try{
            PrintWriter out  = new PrintWriter(new FileWriter(projet_path+"/"+projet+"/option/"+option));
            out.println(value);
            out.close();
          }
          catch(Exception e){
            e.printStackTrace();
          }
    }
    
    private String getOption(String projet, String option)
    {
    	try 
	      {
	      RandomAccessFile raf = new RandomAccessFile(projet_path+"/"+projet+"/option/"+option, "r");
	      return raf.readLine();
	      }
	   catch (IOException e) 
	     {
		   e.printStackTrace();
		   return "";
	     }
    }
    
    private void addSVN(String projet, String path)
    {
    	int i=0;
    	String NomFichier = projet_path+"/"+projet+"/svn/"+i+".txt";
    	while(new File(NomFichier).exists())
    	{
    		i++;
    		NomFichier = projet_path+"/"+projet+"/svn/"+i+".txt";
    	}
        try{
          PrintWriter out  = new PrintWriter(new FileWriter(NomFichier));
          out.println(path);
          out.close();
        }
        catch(Exception e){
          e.printStackTrace();
        }
    }
    
    private ArrayList getSVN(String projet)
    {
    	String[] listeFichiers; 
    	File repertoire = new File(projet_path+"/"+projet+"/svn"); 
    	ArrayList retour= new ArrayList<String>();
    	if(repertoire.exists())
    	{
    	listeFichiers = repertoire.list();
    	for (int i = 0; i < listeFichiers.length; i++) {
    		try 
    	      {
    	      RandomAccessFile raf = new RandomAccessFile(projet_path+"/"+projet+"/svn/"+listeFichiers[i], "r");
    	      String ligne;
    	      ligne = raf.readLine();
    	      if(ligne!=null)retour.add(ligne);
    	      }
    	   catch (IOException e) 
    	     {
    		   e.printStackTrace();
    	     }
    		}
    	}
    	return retour;
    }
}
